// stores/addressStore.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { AddressApi } from '@/api/AddressApi'
import { ElMessage } from 'element-plus'
import { useUserStore } from './userStore'

export const useAddressStore = defineStore('address', () => {
  const addressList = ref([]) // 地址列表
  const defaultAddress = ref(null) // 默认地址
  const loading = ref(false) // 加载状态
  const error = ref(null) // 错误信息

  // 获取用户store
  const userStore = useUserStore()

  /**
   * 初始化地址列表（登录成功后调用）
   */
  const initAddresses = async () => {
    if (!userStore.isLogin) {
      console.log('用户未登录，跳过地址初始化')
      return
    }

    loading.value = true
    error.value = null
    try {
      const response = await AddressApi.getUserAddresses(userStore.userAccount.userId)
      addressList.value = response.data || []

      // 查找并设置默认地址
      defaultAddress.value = addressList.value.find(addr => addr.isDefault) || null
      return addressList.value
    } catch (err) {
      error.value = err.message || '获取地址列表失败'
      console.error('初始化地址失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 新增地址
   * @param {Object} addressDTO 地址信息
   * @returns {Promise} 返回新增的地址数据
   */
 const addAddress = async (addressDTO) => {
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录')
    throw new Error('请先登录')
  }

  loading.value = true
  error.value = null
  try {
    // 设置用户ID
    addressDTO.userId = userStore.userAccount.userId

    // 新增时先不设置默认，统一由setDefaultAddress处理
    const isDefaultRequested = addressDTO.isDefault === 1
    addressDTO.isDefault = 0 // 先设为非默认

    const response = await AddressApi.addAddress(addressDTO)

    // 如果请求设置为默认地址，则调用setDefaultAddress
    if (isDefaultRequested) {
      await setDefaultAddress(response.data.addressId)
    }

    // 添加成功后刷新地址列表
    await initAddresses()

    ElMessage.success('新增地址成功')
    return response.data
  } catch (err) {
    error.value = err.message || '新增地址失败'
    console.error('新增地址失败:', err)
    ElMessage.error(error.value)
    throw err
  } finally {
    loading.value = false
  }
}

  /**
   * 更新地址
   * @param {Object} addressDTO 地址信息
   * @returns {Promise}
   */
  const updateAddress = async (addressDTO) => {
    loading.value = true
    error.value = null
    try {
      const response = await AddressApi.updateAddress(addressDTO)

      // 更新成功后刷新地址列表
      await initAddresses()

      ElMessage.success('更新地址成功')
      return response.data
    } catch (err) {
      error.value = err.message || '更新地址失败'
      console.error('更新地址失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除地址
   * @param {Number} addressId 地址ID
   * @returns {Promise}
   */
  const deleteAddress = async (addressId) => {
    loading.value = true
    error.value = null
    try {
      const userId = userStore.userAccount.userId
      await AddressApi.deleteAddress(addressId, userId)

      // 删除成功后刷新地址列表
      await initAddresses()

      ElMessage.success('删除地址成功')
    } catch (err) {
      error.value = err.message || '删除地址失败'
      console.error('删除地址失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取地址详情
   * @param {Number} addressId 地址ID
   * @returns {Promise}
   */
  const getAddressDetail = async (addressId) => {
    loading.value = true
    error.value = null
    try {
      const userId = userStore.userAccount.userId
      const response = await AddressApi.getAddressDetail(addressId, userId)
      return response.data
    } catch (err) {
      error.value = err.message || '获取地址详情失败'
      console.error('获取地址详情失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 设置默认地址
   * @param {Number} addressId 地址ID
   * @returns {Promise}
   */
  const setDefaultAddress = async (addressId) => {
    loading.value = true
    error.value = null
    try {
      const userId = userStore.userAccount.userId
      await AddressApi.setDefaultAddress(addressId, userId)

      // 设置成功后刷新地址列表
      await initAddresses()

      ElMessage.success('设置默认地址成功')
    } catch (err) {
      error.value = err.message || '设置默认地址失败'
      console.error('设置默认地址失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      loading.value = false
    }
  }

const getDefaultAddressId = async () => {
  loading.value = true
  error.value = null

  try {
    const userId = userStore.userAccount.userId
    const response = await AddressApi.getDefaultAddressId(userId)

    // 正确检查响应状态码
    if (response.code === 1) {
      // 返回 data 字段中的地址ID
      return response.data
    } else {
      // 处理没有默认地址的情况
      ElMessage.warning(response.msg || '用户未设置默认地址')
      return null
    }
  } catch (err) {
    error.value = err.message || '获取默认地址失败'
    console.error('获取默认地址失败:', err)
    ElMessage.error(error.value)
    throw err
  } finally {
    loading.value = false
  }
}

  /**
   * 根据ID获取地址
   * @param {Number} addressId 地址ID
   * @returns {Object|null} 地址对象
   */
  const getAddressById = (addressId) => {
    return addressList.value.find(addr => addr.addressId === addressId) || null
  }

  /**
   * 清空地址数据（退出登录时调用）
   */
  const clearAddresses = () => {
    addressList.value = []
    defaultAddress.value = null
    error.value = null
  }

  return {
    addressList,
    defaultAddress,
    loading,
    error,
    initAddresses,
    addAddress,
    updateAddress,
    deleteAddress,
    getAddressDetail,
    setDefaultAddress,
    getDefaultAddressId,
    getAddressById,
    clearAddresses
  }
})